package me.zhengjie.modules.system.service.apply;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;
import me.zhengjie.exception.CommonUtilException;
import me.zhengjie.modules.system.enums.ApplyWorkOrderTypeEnum;
import me.zhengjie.modules.system.service.IdentityCourseService;
import me.zhengjie.modules.system.service.IdentityItemService;
import me.zhengjie.modules.system.service.dto.DisChangeApplyDto;
import me.zhengjie.modules.system.service.dto.IdentityItemBindCourseWorkOrderDto;
import me.zhengjie.modules.system.service.dto.IdentityItemDto;
import me.zhengjie.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class IdentityItemBindCourseServiceImpl implements IApplyCallbackService{

    @Autowired
    IdentityItemService identityItemService;

    @Autowired
    IdentityCourseService identityCourseService;

    @Override
    public Integer getApplyType() {
        return ApplyWorkOrderTypeEnum.BindIdentity.getType();
    }

    @Override
    public boolean execute(DisChangeApplyDto applyDto) {
        String json = applyDto.getApplyContent();
        if(StringUtils.isEmpty(json)){
            throw new CommonUtilException("申请内容不能为空");
        }
        IdentityItemBindCourseWorkOrderDto identityItemBindCourseWorkOrderDto = JSONUtil.toBean(json, IdentityItemBindCourseWorkOrderDto.class);
        IdentityItemDto identityItemDto = identityItemService.findById(identityItemBindCourseWorkOrderDto.getItemId());
        if(ObjectUtil.isEmpty(identityItemDto)){
            throw new CommonUtilException("身份产品不存在，无法修改权益课程");
        }
        identityItemBindCourseWorkOrderDto.getIdentityCourseList().forEach(s -> s.setIdentityNo(identityItemDto.getItemNo()));
        identityCourseService.deleteByIdentityNo(identityItemDto.getItemNo());
        identityItemBindCourseWorkOrderDto.getIdentityCourseList().forEach(s -> identityCourseService.create(s));
        return true;
    }

}
